package cn.kgc.springboot.controller;

import cn.kgc.springboot.common.CodeMsg;
import cn.kgc.springboot.entity.Menu;
import cn.kgc.springboot.entity.RolePer;
import cn.kgc.springboot.mapper.RolePerMapper;
import cn.kgc.springboot.service.MenuService;
import cn.kgc.springboot.util.LayTable;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: mosin
 * @version: v1.0  2022/8/3
 */
@RestController
@RequestMapping("auth")
public class AuthController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private  RolePerMapper rolePerMapper;

    @RequestMapping("zTree")
    public LayTable  getZTree(){
        List<Menu> list = menuService.list();
        return  new LayTable().setCode(CodeMsg.SUCCESS.getCode()).setMsg(CodeMsg.SUCCESS.getMsg()).setData(list);
    }


    @RequestMapping("selectAllAuths")
    public LayTable  selectAllAuths(){
        List<Menu> list = menuService.list();
        return  new LayTable().setCode(CodeMsg.LAY_SUCCESS.getCode()).setMsg(CodeMsg.LAY_SUCCESS.getMsg()).setData(list);
    }

    //根据角色id  查询当前角色的权限信息
    @RequestMapping("selectAuthByRoleId")
    public List<Integer> selectAuthByRoleId(Integer roleId){

        // 根据角色的id  查询所有的权限信息
        QueryWrapper<RolePer> rolePerQueryWrapper = new QueryWrapper<>();
        rolePerQueryWrapper.eq("role_id", roleId);
        List<RolePer> rolePers = rolePerMapper.selectList(rolePerQueryWrapper);

        //ArrayList<Integer> ids = new ArrayList<>();
        //
        //for (RolePer rolePer : rolePers) {
        //    ids.add(rolePer.getPerId());
        //}

        List<Integer> ids = rolePers.stream().map(rolePer -> {
            return rolePer.getPerId();
        }).collect(Collectors.toList());

        return  ids;
    }

    @RequestMapping("add")
    public LayTable addAuth(Menu menu){

        // 添加权限
        menuService.save(menu);
         return new LayTable().setCode(CodeMsg.SUCCESS.getCode()).setMsg(CodeMsg.SUCCESS.getMsg());
    }

    @RequestMapping("update")
    public LayTable updateAuth(Menu menu){

        menuService.updateById(menu);

        return new LayTable().setCode(CodeMsg.SUCCESS.getCode()).setMsg(CodeMsg.SUCCESS.getMsg());
    }

    @RequestMapping("delete")
    public LayTable deleteAuth(Integer id){

        return menuService.deleteAuth(id);

    }





}
